"""
Short file description.

:Author: Sven Walter <sven.walter@wltr.eu>
:Since: 11.06.2011
"""

import os
from datetime import datetime


from django.core.cache import cache


from .. import settings
from ..models import External
from manager import CACHE_NAME


def cleanup_externals():
    external_path = os.path.join(settings.MEDIA_ROOT, settings.EXTERNAL_PATH)
    try:
        file_list = os.listdir(external_path)
        file_list = [os.path.join(settings.EXTERNAL_PATH, p) for p in file_list]
    except OSError:
        return
    
    # remove files from list, whiche are in the database
    for external in External.objects.all():
        if external.file.name in file_list:
            file_list.remove(external.file.name)
    
    # remove unused files from hdd
    for file_name in file_list:
        os.remove(os.path.join(settings.MEDIA_ROOT, file_name))
        

def cleanup_public_files():
    file_list = os.listdir(settings.CACHE)
    
    cache_ = cache.get(CACHE_NAME) or {}
    
    for manager in cache_.values():
        if manager.get_public_filename() in file_list:
            file_list.remove(manager.get_public_filename())
    
    # remove unused files from hdd
    for file_name in file_list:
        os.remove(os.path.join(settings.CACHE, file_name))


def cronjob():
    for e in External.objects.all():
        if e.next_update < datetime.now():
            e.update()
        elif not e.file_exists:
            e.update()
    
    cleanup_externals()
    cleanup_public_files()


